package com.system.userserver.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.system.commonutils.bean.ApiResult;
import com.system.commonutils.bean.PagesBean;
import com.system.commonutils.bean.SecendMenu;
import com.system.commonutils.pojo.Role;
import com.system.commonutils.utils.RedisUtil;
import com.system.userserver.bean.*;
import com.system.userserver.service.RoleService;
import com.system.userserver.service.UserOauthService;
import com.system.userserver.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

@Api(tags = "用户服务-用户API")
@RestController
@Validated
@RequestMapping(value = "auth")
@DefaultProperties(defaultFallback = "golbalFallback")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserOauthService userOauthService;

    @Autowired
    RoleService roleService;

    @Autowired
    RedisUtil redisUtil;


    @HystrixCommand
    @ApiOperation(value = "管理员用户登录")
    @PostMapping(value = "adminlogin",produces = "application/json;charset=UTF-8")
    public ApiResult adminlogin(String username, String password){
        ApiResult adminlogin = userOauthService.adminlogin(username, password);
        System.out.println(adminlogin);
        return adminlogin;
    }




    @HystrixCommand
    @ApiOperation(value = "添加管理员")
    @PostMapping(value = "addAdminUser",produces = "application/json;charset=UTF-8")
    public ApiResult addAdminUser(
            String username, String password,Integer roleId){
        if(roleId==null){
            roleId=1;
        }
        Boolean aBoolean = userService.addAdminUser(username, password,roleId);
        RoleInfo role = roleService.selectRoleById(roleId);
//        List<SecendMenu> menuByRole = roleService.getMenuByRole(roleId);
//        role.setMenus(menuByRole);
        if(aBoolean){
           return ApiResult.successWithData("添加管理员成功",role);
        }
        return ApiResult.failure("添加管理员失败");
    }

    @HystrixCommand
    @ApiOperation(value = "添加用户")
    @PostMapping(value = "addUser",produces = "application/json;charset=UTF-8")
    public ApiResult addUser(
            String username, String password){
        Boolean aBoolean = userService.addUser(username, password);
        return ApiResult.withBoolean(aBoolean,"添加成功","添加失败");
    }



    @PreAuthorize("isAuthenticated()")
    @HystrixCommand
    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "getUserInfo",produces = "application/json;charset=UTF-8")
    public ApiResult getUserInfo(OAuth2Authentication authentication){
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
        String tokenValue = details.getTokenValue();
        UserInfo userBean = redisUtil.get(tokenValue, UserInfo.class);
        return ApiResult.successWithData(userBean);
    }

    @HystrixCommand
    @ApiOperation(value = "根据用户id获取用户详情")
    @GetMapping(value = "getUserInfoById",produces = "application/json;charset=UTF-8")
    public ApiResult getUserInfoById(Integer userId){
        UserDetail userDetail = userService.selectUserInfo(userId);
        return ApiResult.successWithData(userDetail);
    }

    @HystrixCommand
    @ApiOperation(value = "修改用户状态")
    @GetMapping(value = "updateUserStatue",produces = "application/json;charset=UTF-8")
    public ApiResult updateUserStatue(Integer userId,Integer statue){

        if(statue!=1&&statue!=0){
           return ApiResult.failure("参数错误");
        }
        Boolean aBoolean = userService.updateUserStatue(userId,statue);
        return ApiResult.withBoolean(aBoolean);
    }


    @PreAuthorize("isAuthenticated()")
    @HystrixCommand
    @ApiOperation(value = "用户菜单判断")
    @PostMapping(value = "isUserMenu",produces = "application/json;charset=UTF-8")
    public ApiResult isUserMenu(OAuth2Authentication authentication,String menu){
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
        String tokenValue = details.getTokenValue();
        UserInfo userBean = redisUtil.get(tokenValue, UserInfo.class);
        List<SecendMenu> secendMenus = userBean.getRoles().get(0).getSecendMenus();
        for (SecendMenu secendMenu : secendMenus) {
            String menu_name = secendMenu.getMenu_name();
            if(menu_name.equals(menu)){
                return ApiResult.withBoolean(true);
            }
        }
        return ApiResult.withBoolean(false);
    }

    @HystrixCommand
    @ApiOperation(value = "后期管理员列表")
    @GetMapping(value = "adminList",produces = "application/json;charset=UTF-8")
    public ApiResult adminList(
            @NotNull(message = "page不能为空")@RequestParam(required = false) Integer page,
            @NotNull(message = "size不能为空")@RequestParam(required = false) Integer size){
        PagesBean<Admin> adminPagesBean = userService.adminList(page, size);
        return ApiResult.successWithData(adminPagesBean);
    }

    @HystrixCommand
    @ApiOperation(value = "用户列表")
    @GetMapping(value = "userList",produces = "application/json;charset=UTF-8")
    public ApiResult userList(
            @NotNull(message = "page不能为空")@RequestParam(required = false) Integer page,
            @NotNull(message = "size不能为空")@RequestParam(required = false) Integer size,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String userNickName,
            @RequestParam(required = false) String phone
    ){

        PagesBean<UserItem> adminPagesBean = userService.userList(page,size, userId, userNickName, phone);
        return ApiResult.successWithData(adminPagesBean);
    }











    /**
     * 默认熔断回调
     * @return
     */
    public ApiResult golbalFallback(Throwable throwable){
        String localizedMessage = throwable.getLocalizedMessage();
        throwable.printStackTrace();
        return ApiResult.failure(localizedMessage);
    }
}
